package handler

import (
	"context"
	"encoding/json"
	"errors"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"gorm.io/gorm"
	"service_base_shop/goods_srv/global"
	"strconv"
	"strings"

	//"service_base_shop/goods_srv/model"
	protopb "service_base_shop/goods_srv/proto"
)

type Goods struct {
}


//获取首页
func (this *Goods) GetIndexInfo(ctx context.Context, req *protopb.GetIndexInfoReq) (*protopb.GetIndexInfoRep, error) {
	ggtop := []*protopb.Brand{}
	if err := global.DB.Table("lr_guanggao").Order("sort desc,id asc").Select("id,name,photo").Limit(10).Find(&ggtop).Error; err != nil {
		if !errors.Is(err, gorm.ErrRecordNotFound) {
			return &protopb.GetIndexInfoRep{}, status.Errorf(codes.NotFound, "查询错误")
		}
	}
	for _, v := range ggtop {
		v.Photo = global.DataUrl + v.Photo
	}
	brand := []*protopb.Brand{}
	if err := global.DB.Table("lr_brand").Select("id,name,photo").Limit(20).Find(&brand).Error; err != nil {
		if !errors.Is(err, gorm.ErrRecordNotFound) {
			return &protopb.GetIndexInfoRep{}, status.Errorf(codes.NotFound, "查询错误")
		}
	}
	for _, v := range brand {
		v.Photo = global.DataUrl + v.Photo
	}
	//======================
	//首页培训课程
	//======================

	course := []*protopb.Course{}
	if err := global.DB.Table("lr_course").Select("id,title,intro,photo").Order("id desc").Find(&course).Error; err != nil {
		if !errors.Is(err, gorm.ErrRecordNotFound) {
			return &protopb.GetIndexInfoRep{}, status.Errorf(codes.NotFound, "查询错误")
		}
	}
	for _, v := range course {
		v.Photo = global.DataUrl + v.Photo
	}

	//======================
	//首页推荐产品
	//======================
	pro_list := []*protopb.Prolist{}
	if err := global.DB.Table("lr_product").
		Where("del=0 AND pro_type=1 AND is_down=0 AND type=1").
		Select("id,name,intro,photo_x,price_yh,price,shiyong").
		Order("sort desc,id desc").
		Limit(8).
		Find(&pro_list).
		Error; err != nil {
		if !errors.Is(err, gorm.ErrRecordNotFound) {
			return &protopb.GetIndexInfoRep{}, status.Errorf(codes.NotFound, "查询错误")
		}
	}
	for _, v := range pro_list {
		v.PhotoX = global.DataUrl + v.PhotoX
	}

	//======================
	//首页分类 自己组建数组
	//======================
	indeximg := []*struct {
		Photo string
	}{}
	if err := global.DB.Table("lr_indeximg").Select("photo").Order("id desc").Limit(8).Find(&indeximg).Error; err != nil {
		if !errors.Is(err, gorm.ErrRecordNotFound) {
			return &protopb.GetIndexInfoRep{}, status.Errorf(codes.NotFound, "查询错误")
		}
	}
	procat := make([]*protopb.Procat, 4)
	procat[0] = &protopb.Procat{
		Imgs:  global.DataUrl + indeximg[0].Photo,
		Name:  "新闻资讯",
		Link:  "other",
		Ptype: "news",
	}
	procat[1] = &protopb.Procat{
		Imgs:  global.DataUrl + indeximg[1].Photo,
		Name:  "教学优势",
		Link:  "other",
		Ptype: "jxys",
	}
	procat[2] = &protopb.Procat{
		Imgs:  global.DataUrl + indeximg[2].Photo,
		Name:  "学员风采",
		Link:  "other",
		Ptype: "xyfc",
	}
	procat[3] = &protopb.Procat{
		Imgs:  global.DataUrl + indeximg[3].Photo,
		Name:  "关于我们",
		Link:  "other",
		Ptype: "gywm",
	}

	return &protopb.GetIndexInfoRep{
		Procat:  procat,
		Prolist: pro_list,
		Course:  course,
		Brand:   brand,
		Ggtop:   ggtop,
	}, nil
}



//***************************
//  首页产品 分页
//***************************
func (this *Goods) GetIndexList(ctx context.Context, req *protopb.GetIndexListReq) (*protopb.GetIndexListRep, error) {
	if req.Page == 0 {
		req.Page = 1;
	}
	offset := (req.Page - 1) * 8
	pro_list := []*protopb.Prolist{}
	if ret := global.DB.Table("lr_product").
		Where("del = 0 and pro_type=1 and is_down=0 and type=1").
		Order("sort desc,id desc").
		Select("id,name,photo_x,price_yh,shiyong").
		Offset(int(offset)).Limit(8).Find(&pro_list); ret.RowsAffected == 0 {
		return &protopb.GetIndexListRep{}, status.Errorf(codes.NotFound, "未查询到")
	}
	for _,v := range pro_list{
		v.PhotoX = global.DataUrl + v.PhotoX
	}
	return &protopb.GetIndexListRep{
		List: pro_list,
	},nil
}


//获取商品
func (this *Goods) GetProductInfo(ctx context.Context, req *protopb.GetProductReq) (*protopb.GetProductRep, error) {
	pro := map[string]interface{}{}
	if err := global.DB.Table("lr_product as p").
		Joins("left join lr_brand as b on p.brand_id = b.id").
		Joins("left join lr_category as c on c.id = p.cid").
		Where("p.id = ? and p.del = 0 and p.is_down = 0", req.ProId).
		Select("p.*,b.name as brand, c.name as cat_name").Take(&pro).Error; err != nil {
		if !errors.Is(err, gorm.ErrRecordNotFound) {
			return &protopb.GetProductRep{}, status.Errorf(codes.NotFound, "查询错误")
		} else {
			return &protopb.GetProductRep{}, status.Errorf(codes.NotFound, "商品下价，或不存在")
		}
	}
	pro["photo_x"] = global.DataUrl + pro["photo_x"].(string)
	pro["photo_d"] = global.DataUrl + pro["photo_d"].(string)

	//图片轮播数组
	image := strings.Split(pro["photo_string"].(string), ",")
	image_arr := []string{}
	for _, v := range image {
		if v != "" {
			v = global.DataUrl + v
			image_arr = append(image_arr, v)
		}
	}
	pro["img_arr"] = image_arr //图片轮播数组

	commodityAttr := []map[string]interface{}{} //产品库还剩下的产品规格
	attrValueList := []map[string]interface{}{} //产品所有的产品规格
	if pro["pro_buff"] != nil {
		pro_buff := strings.Split(",", pro["pro_buff"].(string))
		for _, v := range pro_buff {
			attr_name := map[string]string{}
			guigelist := []map[string]interface{}{}
			global.DB.Table("lr_attribute").Where("id = ?", v).Select("attr_name").Take(&attr_name)
			global.DB.Table("lr_guige").Where("pid = ? and  attr_id = ?", pro["id"], v).Select("id,name").Find(&guigelist)
			ggss := []string{}
			gg := []map[string]string{}
			for _, v1 := range guigelist {
				gg = append(gg, map[string]string{"attrKey": attr_name["attr_name"], "attrValue": v1["name"].(string)})
				ggss = append(ggss, v1["name"].(string))
			}
			commodityAttr = append(commodityAttr, map[string]interface{}{"attrValueList": gg})
			attrValueList = append(attrValueList, map[string]interface{}{"attrKey": attr_name["attr_name"], "attrValueList": ggss})
		}
	}
	content := strings.ReplaceAll(pro["content"].(string), "/minipetmrschool/Data/", global.DataUrl)
	pro["content"] = content
	pro["collect"] = 0
	ret_pro_json, _ := json.Marshal(pro)
	commodity_attr_json, _ := json.Marshal(commodityAttr)
	attr_value, _ := json.Marshal(attrValueList)
	return &protopb.GetProductRep{ProInfo: string(ret_pro_json), AttrValueList: string(attr_value), CommodityAttr: string(commodity_attr_json)}, nil
}


//获取分类
func (this *Goods) CateGoryIndex(ctx context.Context, req *protopb.CateGoryReq) (*protopb.CateGoryRep, error) {
	category := []*protopb.GoodsList{}
	if ret :=  global.DB.Table("lr_category").Where("tid = 1").Select("id,tid,name").Find(&category); ret.RowsAffected == 0{
		return nil, status.Errorf(codes.NotFound, "查询错误")
	}
	catList := []*protopb.CatList{}

	if ret := global.DB.Table("lr_category").Where("tid = ?",category[0].Id).Select("id,name,bz_1").Find(&catList); ret.RowsAffected == 0 {
		return nil, status.Errorf(codes.NotFound, "查询错误!")
	}
	for _,v := range catList{
		v.Bz_1 = global.DataUrl + v.Bz_1
	}
	return &protopb.CateGoryRep{CatList: catList,List: category}, nil
}



//获取分类
func (this *Goods) GetGatGoryByCatId(ctx context.Context, req *protopb.GetGatGoryByCatIdReq) (*protopb.GetGatGoryByCatIdRep, error) {
	catList := []*protopb.CatList{}
	if ret := global.DB.Table("lr_category").Where("tid = ?",req.CatId).Select("id,name,bz_1").Find(&catList); ret.RowsAffected == 0 {
		return nil, status.Errorf(codes.NotFound, "查询错误!")
	}
	for _,v := range catList{
		v.Bz_1 = global.DataUrl + v.Bz_1
	}
	return &protopb.GetGatGoryByCatIdRep{List: catList}, nil
}

/**
分类列表页商品
 */
func (this *Goods) GetGatGoryList(ctx context.Context, req *protopb.GetGatGoryListReq) (*protopb.GetGatGoryListRep, error) {
	id := req.CatId
	brand_id := req.BrandId
	ptype := req.Ptype
	keyword := req.Keyword
	page := req.Page
	//排序
	order := "addtime desc"
	if ptype == "ids" {
		order ="id desc"
	}else if ptype == "sale" {
		order ="shiyong desc"
	}else if ptype == "price" {
		order ="price_yh desc"
	}else if ptype == "hot" {
		order ="renqi desc"
	}
	//条件
	where := "pro_type=1 AND del=0 AND is_down = 0"
	if id > 0 {
		where += " and cid = " + strconv.Itoa(int(id))
	}
	if brand_id  > 0{
		where += " and brand_id = " + strconv.Itoa(int(brand_id))
	}
	if keyword  != "" {
		where += ` and name like "`+ keyword +`"`
	}
	if ptype == "new" {
		where += " and is_show = 1"
	}
	if ptype == "hot" {
		where += " and is_hot = 1"
	}
	if ptype == "zk" {
		where += " and is_sale = 1"
	}
	list := []*protopb.Prolist{}
	if page == 0{
		page = 1
	}
	if ret := global.DB.Table("lr_product").Where(where).Order(order).Offset((int(page) - 1) * 6).Limit(6).Find(&list); ret.RowsAffected == 0 {
		return nil, status.Errorf(codes.NotFound, "暂无数据")
	}
	for _,v := range list{
		v.PhotoX = global.DataUrl + v.PhotoX
	}
	cat := protopb.CatList{}
	if ret := global.DB.Table("lr_category").Where("id = ?",id).Select("name").Take(&cat); ret.RowsAffected == 0 {
		return nil, status.Errorf(codes.NotFound, "查询错误1!")
	}
	return &protopb.GetGatGoryListRep{List: list,CatName: cat.Name}, nil
}

